package com.haierCamera.customapplication.ui;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.haierCamera.customapplication.BaseFragment;
import com.haierCamera.customapplication.Constants;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.ApiService;
import com.haierCamera.customapplication.api.vo.GetDeviceEntity;
import com.haierCamera.customapplication.databinding.HzklFragmentHomeBinding;
import com.haierCamera.customapplication.ui.business.Business;
import com.haierCamera.customapplication.ui.custom.BaseListenerOnClik;
import com.haierCamera.customapplication.ui.custom.LinearLayoutColorDivider;
import com.haierCamera.customapplication.ui.login.HZKLLoginActivity;
import com.haierCamera.customapplication.ui.login.HZKLLoginWelcomeActivity;
import com.haierCamera.customapplication.ui.login.HZKLWelcomeActivity;
import com.haierCamera.customapplication.ui.main.CameraDeviceListAdapter;

import com.haierCamera.customapplication.ui.main.HZKLCameraDeviceAddStepOneActivity;
import com.haierCamera.customapplication.ui.main.HZKLCameraDeviceDetailActivity;
import com.haierCamera.customapplication.ui.main.HZKLDeviceSearchActivity;

import com.haierCamera.customapplication.ui.main.HZKLMsgAlarmSettingActivity;
import com.haierCamera.customapplication.ui.main.HZKLRecordListAllActivity;
import com.haierCamera.customapplication.ui.main.widget.DialogEditDevice;
import com.haierCamera.customapplication.ui.mediaplay.MediaPlayActivity;
import com.haierCamera.customapplication.ui.user.activity.HZKLRepairActivity;
import com.haierCamera.customapplication.ui.zxing.activity.CaptureActivity;
import com.haierCamera.customapplication.utils.DateUtil;
import com.haierCamera.customapplication.utils.DensityUtil;
import com.haierCamera.customapplication.utils.NoDoubleClickListener;
import com.haierCamera.customapplication.utils.ResourceConvertUtils;
import com.haierCamera.customapplication.utils.SharedPreferencesUtils;
import com.haierCamera.customapplication.utils.StringUtils;
import com.haierCamera.customapplication.utils.android.HttpErrorProcess;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import dagger.Lazy;

public class HomeFragment extends BaseFragment {

//    @Inject
//    ViewModelProvider.Factory factory;
    @Inject
    Lazy<HttpErrorProcess> httpErrorProcessLazy;
    @Inject
    ApiService apiService;

    HzklFragmentHomeBinding binding;
    CameraDeviceListAdapter adapter;
    List<GetDeviceEntity> list;

    int pushState = -1;

    FragmentActivity activity;

    public void setActivity(FragmentActivity activity) {
        this.activity = activity;
    }

    private ProgressDialog mLoadingDialog;
    public void showLoadingDialog() {
        if (null == mLoadingDialog) {
            return;
        }
        mLoadingDialog.setCanceledOnTouchOutside(true);
        mLoadingDialog.show();
    }

    public void dismissLoadingDialog() {
        if (null == mLoadingDialog) {
            return;
        }
        mLoadingDialog.dismiss();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.hzkl_fragment_home, container, false);

        binding.includeLayout.loginBtn.setOnClickListener(view -> startActivity(new Intent(getActivity(), HZKLLoginWelcomeActivity.class)));
//        processWithPermission(()->{}, Manifest.permission.ACCESS_COARSE_LOCATION);
//        processWithPermission(()->{}, Manifest.permission.ACCESS_FINE_LOCATION);

//        binding.ivEditView.setOnClickListener((v)->{
//
//            if (adapter.getType() == 0) {
//                binding.rcv.setLayoutManager(new GridLayoutManager(getActivity(), 2));
//                binding.rcv.removeItemDecorationAt(0);
//                binding.rcv.addItemDecoration(new GridLayoutColorDivider(getActivity()
//                            , 0x00000000
//                            , DensityUtil.dip2px(getActivity(), 5)
//                            , DensityUtil.dip2px(getActivity(), 5)));
//                adapter.setType(1);
//                binding.ivEditView.setImageResource(R.drawable.hzkl_home_edit_view_lin);
//
//            } else if (adapter.getType() == 1) {
//                binding.rcv.setLayoutManager(new LinearLayoutManager(getActivity()));
//                binding.rcv.removeItemDecorationAt(0);
//                binding.rcv.addItemDecoration(new LinearLayoutColorDivider(getActivity()
//                        , 0x00000000
//                        , DensityUtil.dip2px(getActivity(), 5)
//                        , DensityUtil.dip2px(getActivity(), 5)));
//                adapter.setType(0);
//                binding.ivEditView.setImageResource(R.drawable.hzkl_home_edit_view);
//
//            }
//        });

        binding.edSearch.setOnClickListener((v)->{
            startActivity(new Intent(getActivity(), HZKLDeviceSearchActivity.class));
        });

        binding.swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getDevice();
                getPush();
            }
        });


        adapter= new CameraDeviceListAdapter(getActivity());
        binding.rcv.setLayoutManager(new LinearLayoutManager(getActivity()));
//        binding.rcv.setLayoutManager(new GridLayoutManager(getActivity(),2));
        binding.rcv.setAdapter(adapter);
        binding.rcv.addItemDecoration(new LinearLayoutColorDivider(getActivity()
                ,0x00000000
                , DensityUtil.dip2px(getActivity(),5)
                ,DensityUtil.dip2px(getActivity(),5)));
        adapter.setType(0);
        adapter.setActivity(getActivity());

        binding.ivState.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (pushState == -1) {
                    toast("未获取推送状态");
                    return;
                }
                if (pushState == 0) {
                    setPush(1);
                } else if ( pushState == 1){
                    setPush(0);
                }
            }
        });

        binding.ivAddCamera.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {

                processWithPermission(()->{
                    Log.i("TAG","runnable---");
                    startActivityForResult(new Intent(getActivity()
                            , CaptureActivity.class)
                            .putExtra("type","1"),100);

                }, Manifest.permission.CAMERA);

            }
        });

//        binding.layoutMonitor.setOnClickListener((v)->{
//            startActivity(new Intent(getActivity()
//                    , HZKLMyCameraDeviceActivity.class));
//        });
//        binding.layoutDoorLock.setOnClickListener((v)->{
//            startActivity(new Intent(getActivity()
//                    , HZKLBlankActivity.class)
//            .putExtra("title","四川广电门锁"));
//        });
//        binding.layoutAlarm.setOnClickListener((v)->{
//            startActivity(new Intent(getActivity()
//                    , HZKLBlankActivity.class)
//                    .putExtra("title","四川广电报警"));
//        });
//        binding.layoutPeepHole.setOnClickListener((v)->{
//            startActivity(new Intent(getActivity()
//                    , HZKLBlankActivity.class)
//                    .putExtra("title","四川广电猫眼"));
//        });
        binding.tvDate.setText(DateUtil.getNowTime2() + DateUtil.getDayString(DateUtil.getDayofWeek()));

        mLoadingDialog = new ProgressDialog(getActivity());
        mLoadingDialog.setMessage("请稍后");

        return binding.getRoot();
    }

    /**
     * 获取SSID
     * @param activity 上下文
     * @return  WIFI 的SSID
     */
    public String getWIFISSID(Activity activity) {
        String ssid="unknown id";

        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O||Build.VERSION.SDK_INT== Build.VERSION_CODES.P) {

            WifiManager mWifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

            assert mWifiManager != null;
            WifiInfo info = mWifiManager.getConnectionInfo();

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                return info.getSSID();
            } else {
//                return info.getSSID().replace(""", "");
                return info.getSSID().replace("\"","");
            }
        } else if (Build.VERSION.SDK_INT==Build.VERSION_CODES.O_MR1){

            ConnectivityManager connManager = (ConnectivityManager) activity.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            assert connManager != null;
            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            if (networkInfo.isConnected()) {
                if (networkInfo.getExtraInfo()!=null){
//                    return networkInfo.getExtraInfo().replace(""","");
                    return networkInfo.getExtraInfo().replace("\"","");
                }
            }
        }
        return ssid;
    }

    private void getPush(){
        ResourceConvertUtils.convertToResource(apiService.getSendSetting())
                .observe(this, resource -> {
                    assert resource != null;
                    switch (resource.status) {
                        case ERROR:
                            httpErrorProcessLazy.get().process(resource);
//                            binding.swipe.setRefreshing(false);
                            break;
                        case SUCCESS:
                            if (resource.data.pushState == 0) {
                                binding.ivState.setImageResource(R.drawable.hzkl_home_accept_msg_not);
                                pushState = 0;
                            } else if (resource.data.pushState == 1) {
                                binding.ivState.setImageResource(R.drawable.hzkl_home_accept_msg);
                                pushState = 1;
                            }

                            break;
                        case LOADING:
                            break;

                    }
                });
    }

    private void setPush(int t) {
        ResourceConvertUtils.convertToResource(apiService.setSendSetting2(t))
                .observe(this, resource -> {
                    assert resource != null;
                    switch (resource.status) {
                        case ERROR:
                            httpErrorProcessLazy.get().process(resource);
//                            binding.swipe.setRefreshing(false);
                            break;
                        case SUCCESS:
                            if (t == 0) {
                                binding.ivState.setImageResource(R.drawable.hzkl_home_accept_msg_not);
                                pushState = 0;
                            } else if (t == 1) {
                                binding.ivState.setImageResource(R.drawable.hzkl_home_accept_msg);
                                pushState = 1;
                            }


                            break;
                        case LOADING:
                            break;

                    }
                });
    }
    public void getDevice() {
        ResourceConvertUtils.convertToResource(apiService.getDevice())
                .observe(this, resource -> {
                    assert resource != null;
                    switch (resource.status) {
                        case ERROR:
                            httpErrorProcessLazy.get().process(resource);
                            binding.swipe.setRefreshing(false);
                            break;
                        case SUCCESS:

                            list = resource.data;
                            binding.swipe.setRefreshing(false);
                            adapter.upDate(resource.data);
                            Business.getInstance().setmDeviceList(resource.data);

                            adapter.setOnItemOnClick(new BaseListenerOnClik() {
                                @Override
                                public void onClick(int position) {
                                    getDeviceChannel(list.get(position).serialNumber,position);
                                }
                            });

                            if (list.size() >0) {
                                binding.rcv.setVisibility(View.VISIBLE);
                                binding.ivEmpty.setVisibility(View.GONE);
                            } else {
                                binding.rcv.setVisibility(View.GONE);
                                binding.ivEmpty.setVisibility(View.VISIBLE);
                            }
                            break;
                        case LOADING:
                            break;

                    }
                });
    }

    private void getDeviceChannel(String sn ,int i){
        showLoadingDialog();
        Business.getInstance().getDeviceInfo2(sn,new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                Log.i("TAG","getDeviceChannel-" + msg.what);
                Log.e("TAG","RESABILITY-" + ((Bundle) msg.obj).getString("ability"));
                if (msg.what == 0) {
                    Log.i("TAG","size-" + ((Bundle) msg.obj).getIntegerArrayList("list").size());

                    for (int j = 0; j < ((Bundle) msg.obj).getIntegerArrayList("list").size(); j++) {
                        Log.i("TAG","getDeviceChannel-" + ((Bundle) msg.obj).getIntegerArrayList("list").get(j));
                    }
                    dismissLoadingDialog();
                    startActivity(new Intent(getActivity(), MediaPlayActivity.class)
                            .putExtra("TYPE", 1)
                            .putExtra("RESID", "0")
                            .putExtra("RESDEVICEID", list.get(i).serialNumber)
                            .putExtra("RESPWD", list.get(i).securityCode)
                            .putExtra("RESNAME", list.get(i).name)
                            .putExtra("RESACCOUNTDEVICEID", list.get(i).accountDeviceId)
                            .putExtra("RESPICTURE", list.get(i).picture)
                            .putExtra("RESABILITY", ((Bundle) msg.obj).getString("ability"))
                            .putExtra("RESCHANNELS", ((Bundle) msg.obj).getIntegerArrayList("list")));
                } else {
                    toast("请求失败-" + msg.obj.toString());
                    dismissLoadingDialog();
                }

            }
        });
    }

    /**
     * [获取应用程序版本名称信息]
     * @param context
     * @return 当前应用的版本名称
     */
    public static synchronized String getPackageName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.packageName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private JSONObject parseJson(String string){
        // { 后面
        // } 前面
        // : 前面和后面
        // , 前面和后面
        string = string.replaceAll("\\{","{\"");
        string = string.replaceAll("\\}","\"}");
        string = string.replaceAll(":","\":\"");
        string = string.replaceAll(",","\",\"");
        JSONObject json = null;
        try {
            json = new JSONObject(string);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return  json;

    }

    @Override
    public void onResume() {
        super.onResume();

        String token = SharedPreferencesUtils.getString(Constants.SP_USER_TOKEN, "");
        if (TextUtils.isEmpty(token)) {
            binding.scv.setVisibility(View.GONE);
            binding.layoutNotLogin.setVisibility(View.VISIBLE);
        } else {
            binding.scv.setVisibility(View.VISIBLE);
            binding.layoutNotLogin.setVisibility(View.GONE);
            getPush();
            getDevice();

        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("TAG","HomeFragment-onActivityResult-result-" + resultCode + "/" + "requestCode-" + requestCode);
        if (resultCode == -1){
            switch (requestCode) {
                case 100:
                    Log.i("TAG","getData-" + data.getExtras().getString("result"));
                    String sn = data.getExtras().getString("sn");
                    String sc = data.getExtras().getString("sc");
                    String dt = data.getExtras().getString("dt");
//                    JSONObject json = parseJson(s);
//
//                    if (json != null) {
//                        String sn = "";
//                        try {
//                            sn = json.getString("SN");
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//
//
//
//                        String sc = "";
//                        if (s != null && s.contains("SC:")) {
//
//                            try {
//                                sc = json.getString("SC");
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        } else if (s != null && s.contains("RC:")) {
//                            try {
//                                sc = json.getString("RC");
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        }
                    Log.i("TAG","sn-" +sn + "/sc-" + sc);
                    getActivity().startActivity(new Intent(getActivity(), HZKLCameraDeviceAddStepOneActivity.class)
                            .putExtra("sn", sn)
                            .putExtra("sc", sc)
                            .putExtra("dt", dt));

//                    }
                    break;
                default:
                    break;
            }
        }
    }


}
